<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>YBlog安装程序</title>
<style type="text/css">
<!--
body {
	font-family: Arial;
	font-size: 12px;
	line-height:150%;
}
.main {
	background-color:#FFFFFF;
	margin-top:20px;
	font-size: 12px;
	color: #666666;
	width:500px;
	margin:10px 200px;
	padding:10px;
	list-style:none;
}
input {
	border: 1px solid #CCCCCC;
	font-family: Arial;
	font-size: 12px;
	background-color:#F7F7F7;
	color: #666666;
}
.title{
	font-size:20px;
	font-weight:bold;
}
.title2{
	font-size:14px;
	color:#000000;
	border-bottom: #CCCCCC 1px solid;
}
-->
</style>
</head>
<body>
<div class="main">
<div>
<p><span class="title">YBlog安装程序</span></p>
</div>
<?php
//由于用户可能对BlogApp和Admin文件夹改名,所以不能直接删除缓存
function clearCache($path = '')
{
   if(empty($path))	
		$path = "./";
	
   if(!stristr($path,"ThinkPHP"))
   {
	   if($handle = @opendir($path))
	   {
		   while(false !== ($file = readdir($handle)))
		   {
			   if($file != '.' && $file != '..')
			   {
				   $file = $path.$file ;
				   if(!is_dir($file))
				   {
						$file = str_replace("\\","/",$file);
						if(strstr($file,"/Cache/") || strstr($file,"/Data/") || strstr($file,"/Logs/") || strstr($file,"/Temp/") || strstr($file,"/Html/"))
						{
							unlink($file);
						}
				   }
				   else
				   {
					   $result = clearCache($file.'/');
				   }
			   }
		   }
		   closedir ( $handle ) ;
	   }
   }
}

function checkWriteable($path = '')
{
	global $dirWriteable;

	if(empty($path))	
		$path = "./";
	
	if($path == "./")
	{
		if(is_writeable($path)) {
			echo $path." ... 可写<br />";
		} else {
			echo $path." ... <font color=\"red\">不可写<br /></font>";
			$dirWriteable = false;
		}
	}

	if(!stristr($path,"ThinkPHP"))
    {
	   if($handle = @opendir($path))
	   {
		   while(false !== ($file = readdir($handle)))
		   {
			   if($file != '.' && $file != '..')
			   {
				   $file = $path.$file;
				   if(is_dir($file))
				   {
						$file = $file."/";
						$file = str_replace("\\","/",$file);
						if(strstr($file,"/Cache/") || strstr($file,"/Data/") || strstr($file,"/Logs/") || strstr($file,"/Temp/") || strstr($file,"/Html/") || strstr($file,"/Uploads/"))
						{
							if(is_writeable($file)) {
								echo $file." ... 可写<br />";
							} else {
								echo $file." ... <font color=\"red\">不可写<br /></font>";
								$dirWriteable = false;
							}
						}

						checkWriteable($file);
				   }
			   }
		   }
		   closedir ( $handle ) ;
	   }
	}
}

function error($msg)
{
	die('<font color="red">'.$msg.'<br></font></body></html>');
}

if(file_exists("db_config.php"))
	error("请先删除 db_config.php 文件再执行安装");

if(isset($_POST["install"]))
{
	echo "<h3>第三步 建数据库、保存配置</h3>";
	
	foreach($_POST as $key=>$value)
		if($key != "DB_PWD" && empty($value))
			error("安装数据项填写不完整");

	if($_POST["user_pass2"] != $_POST["user_pass"])
		error("管理员密码与输入的确认密码不一致");

	$db = mysql_connect($_POST["DB_HOST"].":".$_POST["DB_PORT"],$_POST["DB_USER"],$_POST["DB_PWD"]);
	if(!$db)
		error("无法连接数据库");

	$resource = mysql_query("SHOW DATABASES");
	$findDB = false;
	while($database = mysql_fetch_array($resource))
	{
		if(strtoupper($database[0]) == strtoupper($_POST["DB_NAME"]))
		{
			$findDB = true;
			break;
		}
	}

	if(!$findDB)
	{
		//没有现成的数据库,尝试新建一个库
		if(mysql_get_server_info() > '4.1')
			$createSql = "CREATE DATABASE `".$_POST["DB_NAME"]."` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
		else
			$createSql = "CREATE DATABASE `".$_POST["DB_NAME"]."`";
		mysql_query($createSql,$db) or error("无法创建数据库 ".$_POST["DB_NAME"]);
	}

	mysql_select_db($_POST["DB_NAME"],$db) or error("无法使用数据库 ".$_POST["DB_NAME"]);
	mysql_query("SET NAMES 'utf8'");
	
	//$_POST["siteurl"]这个值如果用户在最后写上了/,把/去掉
	if(substr($_POST["siteurl"],strlen($_POST["siteurl"])-1) == '/')
	   $_POST["siteurl"] = substr($_POST["siteurl"],0,strlen($_POST["siteurl"])-1);

	$suffix = mysql_get_server_info() > '4.1' ? "ENGINE=MyISAM DEFAULT CHARSET=utf8" : " TYPE=MyISAM";
	$install = "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";
	DROP TABLE IF EXISTS `".$_POST["DB_PREFIX"]."attach`;
	CREATE TABLE `".$_POST["DB_PREFIX"]."attach` (
	  `id` int(11) NOT NULL auto_increment,
	  `name` varchar(255) NOT NULL,
	  `type` varchar(255) default NULL,
	  `size` varchar(20) NOT NULL,
	  `extension` varchar(20) NOT NULL,
	  `savepath` varchar(255) NOT NULL,
	  `savename` varchar(255) NOT NULL,
	  `postId` int(11) NOT NULL default '0',
	  `userId` int(11) unsigned default NULL,
	  `uploadTime` int(11) unsigned default NULL,
	  `downCount` mediumint(9) unsigned default '0',
	  `remark` varchar(255) NOT NULL,
	  `inserted` char(1) NOT NULL default '0',
	  PRIMARY KEY  (`id`)
	) ".$suffix.";
	DROP TABLE IF EXISTS `".$_POST["DB_PREFIX"]."category`;
	CREATE TABLE `".$_POST["DB_PREFIX"]."category` (
	  `cid` int(11) NOT NULL auto_increment,
	  `name` varchar(200) NOT NULL default '',
	  `slug` varchar(200) NOT NULL default '',
	  `description` varchar(255) default NULL,
	  `count` int(11) NOT NULL default '0',
	  PRIMARY KEY  (`cid`),
	  UNIQUE KEY `slug` (`slug`)
	) ".$suffix.";
	INSERT INTO `".$_POST["DB_PREFIX"]."category` (`cid`, `name`, `slug`, `description`, `count`) VALUES
	(1, '默认分类', 'default', NULL, 1);
	DROP TABLE IF EXISTS `".$_POST["DB_PREFIX"]."comments`;
	CREATE TABLE `".$_POST["DB_PREFIX"]."comments` (
	  `comment_ID` int(10) unsigned NOT NULL auto_increment,
	  `comment_post_ID` int(11) NOT NULL default '0',
	  `comment_author` tinytext NOT NULL,
	  `comment_author_email` varchar(100) NOT NULL default '',
	  `comment_author_url` varchar(200) NOT NULL default '',
	  `comment_author_IP` varchar(100) NOT NULL default '',
	  `comment_date` datetime NOT NULL default '0000-00-00 00:00:00',
	  `comment_content` text NOT NULL,
	  `comment_approved` varchar(20) NOT NULL default '1',
	  `comment_type` varchar(10) NOT NULL default 'comment',
	  PRIMARY KEY  (`comment_ID`),
	  KEY `comment_approved` (`comment_approved`),
	  KEY `comment_post_ID` (`comment_post_ID`)
	) ".$suffix.";
	INSERT INTO `".$_POST["DB_PREFIX"]."comments` (`comment_ID`, `comment_post_ID`, `comment_author`, `comment_author_email`, `comment_author_url`, `comment_author_IP`, `comment_date`, `comment_content`, `comment_approved`, `comment_type`) VALUES
	(1, 1, '游客', 'guest@site.com', '', '127.0.0.1', NOW(), '这是一条测试评论', '1', 'comment');
	DROP TABLE IF EXISTS `".$_POST["DB_PREFIX"]."links`;
	CREATE TABLE `".$_POST["DB_PREFIX"]."links` (
	  `link_id` int(11) NOT NULL auto_increment,
	  `link_url` varchar(255) NOT NULL default '',
	  `link_name` varchar(255) NOT NULL default '',
	  `link_target` varchar(25) NOT NULL default '_blank',
	  `link_description` varchar(255) NOT NULL default '',
	  `link_rating` int(11) NOT NULL default '255',
	  PRIMARY KEY  (`link_id`)
	) ".$suffix.";
	INSERT INTO `".$_POST["DB_PREFIX"]."links` (`link_id`, `link_url`, `link_name`, `link_target`, `link_description`, `link_rating`) VALUES
	(1, 'http://www.yhustc.com', 'YBlog', '_blank', 'YBlog', 0),
	(2, 'http://www.thinkphp.cn', 'ThinkPHP框架', '_blank', 'ThinkPHP框架', 0);
	DROP TABLE IF EXISTS `".$_POST["DB_PREFIX"]."options`;
	CREATE TABLE `".$_POST["DB_PREFIX"]."options` (
	  `option_name` varchar(64) NOT NULL default '',
	  `option_value` text NOT NULL,
	  `autoload` varchar(20) NOT NULL default 'yes',
	  PRIMARY KEY  (`option_name`)
	) ".$suffix.";
	INSERT INTO `".$_POST["DB_PREFIX"]."options` (`option_name`, `option_value`, `autoload`) VALUES
	('siteurl', '".$_POST["siteurl"]."', 'yes'),
	('blogname', '一个全新的YBlog', 'yes'),
	('blogdescription', '基于ThinkPHP框架的单用户Blog', 'yes'),
	('sitekeywords', 'YBlog,thinkphp', 'yes'),
	('admin_email', '".$_POST["user_email"]."', 'yes'),
	('use_balanceTags', '0', 'yes'),
	('require_name_email', '1', 'yes'),
	('comments_notify', '0', 'yes'),
	('posts_per_rss', '10', 'yes'),
	('rss_use_excerpt', '1', 'yes'),
	('mailserver_url', 'mail.example.com', 'yes'),
	('mailserver_email', 'login@example.com', 'yes'),
	('mailserver_login', 'login@example.com', 'yes'),
	('mailserver_pass', 'password', 'yes'),
	('mailserver_port', '25', 'yes'),
	('default_category', '2', 'yes'),
	('default_comment_status', 'open', 'yes'),
	('default_ping_status', 'open', 'yes'),
	('posts_per_page', '8', 'yes'),
	('comment_moderation', 'closed', 'yes'),
	('comment_min_length', '5', 'yes'),
	('moderation_keys', '法轮\r\n色情\r\n艳照\r\n网址大全\r\n群发软件\r\n切听器\r\n私家侦探\r\n情色\r\n黄站\r\n热门电影\r\n免费下载\r\n专业网站', 'yes'),
	('blog_public', 'open', 'yes'),
	('comments_order', 'asc', 'yes'),
	('icp_information', '', 'yes'),
	('auto_save_time', '5', 'yes'),
	('close_reason', '我正在对站点做清理工作', 'yes'),
	('auto_post_name', 'true', 'yes');
	DROP TABLE IF EXISTS `".$_POST["DB_PREFIX"]."plugin`;
	CREATE TABLE `".$_POST["DB_PREFIX"]."plugin` (
	  `id` mediumint(8) unsigned NOT NULL auto_increment,
	  `name` varchar(255) NOT NULL,
	  `author` varchar(255) NOT NULL,
	  `description` text NOT NULL,
	  `status` tinyint(1) unsigned NOT NULL,
	  `version` varchar(10) NOT NULL,
	  `uri` varchar(255) NOT NULL,
	  `file` varchar(255) NOT NULL,
	  `priority` tinyint(4) NOT NULL default '100',
	  `type` varchar(10) NOT NULL default 'plugin',
	  PRIMARY KEY  (`id`)
	) ".$suffix.";
	DROP TABLE IF EXISTS `".$_POST["DB_PREFIX"]."posts`;
	CREATE TABLE `".$_POST["DB_PREFIX"]."posts` (
	  `ID` int(10) unsigned NOT NULL auto_increment,
	  `post_author` int(11) NOT NULL default '0',
	  `post_date` datetime NOT NULL default '0000-00-00 00:00:00',
	  `post_content` longtext NOT NULL,
	  `post_title` text NOT NULL,
	  `top` char(1) NOT NULL default '0',
	  `post_category` int(4) NOT NULL default '0',
	  `post_status` varchar(20) NOT NULL default 'publish',
	  `comment_status` varchar(20) NOT NULL default 'open',
	  `ping_status` varchar(20) NOT NULL default 'open',
	  `post_name` varchar(255) NOT NULL default '',
	  `post_modified` datetime NOT NULL default '0000-00-00 00:00:00',
	  `post_type` varchar(20) NOT NULL default 'post',
	  `comment_count` int(11) NOT NULL default '0',
	  PRIMARY KEY  (`ID`),
	  KEY `post_name` (`post_name`)
	) ".$suffix.";
	INSERT INTO `".$_POST["DB_PREFIX"]."posts` (`ID`, `post_author`, `post_date`, `post_content`, `post_title`, `top`, `post_category`, `post_status`, `comment_status`, `ping_status`, `post_name`, `post_modified`, `post_type`, `comment_count`) VALUES
	(1, 1, NOW(), '<p>欢迎使用YBlog博客程序，这是系统自带的一篇用于测试的日志。</p><p>YBlog是基于<a target=\"_blank\" href=\"http://www.thinkphp.cn\">ThinkPHP</a>框架的单用户博客系统，继承自ThinkPHP的相关特性，YBlog支持多模板、插件机制、HTML静态缓存等众多特性，想要了解YBlog有关的最新开发进展和开发教程，欢迎访问<a target=\"_blank\" href=\"http://www.yhustc.com\">YBlog官方网站</a></p><p>赶快登录后台，开启侧边栏的widget，开始体验YBlog吧！</p>', '这是一篇测试日志', '0', 1, 'publish', 'open', 'open', '', NOW(), 'post', 1);
	DROP TABLE IF EXISTS `".$_POST["DB_PREFIX"]."tags`;
	CREATE TABLE `".$_POST["DB_PREFIX"]."tags` (
	  `postid` int(11) NOT NULL auto_increment,
	  `tag_name` varchar(255) NOT NULL,
	  PRIMARY KEY  (`postid`,`tag_name`)
	) ".$suffix.";
	INSERT INTO `".$_POST["DB_PREFIX"]."tags` (`postid`, `tag_name`) VALUES (1, '测试');
	DROP TABLE IF EXISTS `".$_POST["DB_PREFIX"]."user`;
	CREATE TABLE `".$_POST["DB_PREFIX"]."user` (
	  `ID` int(10) unsigned NOT NULL auto_increment,
	  `user_login` varchar(60) NOT NULL default '',
	  `user_pass` varchar(64) NOT NULL default '',
	  `user_email` varchar(100) NOT NULL default '',
	  `user_registered` datetime NOT NULL default '0000-00-00 00:00:00',
	  `user_status` int(11) NOT NULL default '1',
	  PRIMARY KEY  (`ID`)
	) ".$suffix.";
	INSERT INTO `".$_POST["DB_PREFIX"]."user` (`ID`, `user_login`, `user_pass`, `user_email`, `user_registered`, `user_status`) VALUES
	(1, '".$_POST["user_login"]."', '".md5($_POST["user_pass"])."', '".$_POST["user_email"]."', NOW(), 1);
	DROP TABLE IF EXISTS `".$_POST["DB_PREFIX"]."usermeta`;
	CREATE TABLE `".$_POST["DB_PREFIX"]."usermeta` (
	  `umeta_id` int(11) NOT NULL auto_increment,
	  `user_id` int(11) NOT NULL default '0',
	  `display_name` varchar(250) default NULL,
	  `user_picture` varchar(255) default NULL,
	  `user_url` varchar(250) default NULL,
	  `qq` varchar(15) default NULL,
	  `msn` varchar(50) default NULL,
	  `age` tinyint(4) default NULL,
	  `location` varchar(250) default NULL,
	  PRIMARY KEY  (`umeta_id`)
	) ".$suffix.";
	INSERT INTO `".$_POST["DB_PREFIX"]."usermeta` (`umeta_id`, `user_id`, `display_name`, `user_url`, `qq`, `msn`, `age`, `location`) VALUES
	(1, 1, '".$_POST["user_login"]."', NULL, NULL, NULL, NULL, NULL);";

	$sqlArray = explode(";\r\n",$install);
	foreach($sqlArray as $sql)
	{
		mysql_query(str_replace("\r\n","",trim($sql)),$db) or error("执行SQL出错: <br>".str_replace("\r\n","<br>",trim($sql)));
		if(preg_match('/^CREATE TABLE `(.*?)`/',str_replace("\r\n","",trim($sql)),$regs))
			echo '新建数据表"'.$regs[1].'" ... 完成<br>';
	}

	//所有SQL执行完成,保存数据库配置
	$db_config = "<?php\r\nif (!defined('THINK_PATH')) exit();\r\nreturn array(\r\n\t'DB_TYPE'=>'mysql',\r\n\t'DB_HOST'=>'".$_POST["DB_HOST"]."',\r\n\t'DB_NAME'=>'".$_POST["DB_NAME"]."',\r\n\t'DB_USER'=>'".$_POST["DB_USER"]."',\r\n\t'DB_PWD'=>'".$_POST["DB_PWD"]."',\r\n\t'DB_PORT'=>'".$_POST["DB_PORT"]."',\r\n\t'DB_PREFIX'=>'".$_POST["DB_PREFIX"]."',\r\n\t'DB_CHARSET'=>'utf8'\r\n);\r\n?>";
	file_put_contents("db_config.php",$db_config);

	//为了防止用户是重复安装,清空一下缓存
	clearCache();

	echo '安装完成，去看看你的新博客吧！ <a href="'.$_POST["siteurl"].'">Go&gt;&gt;</a>';
}
else if($_GET["step"] == "1")
{
	echo "<p class='title2'>第一步 目录属性检查</p>";
	$dirWriteable = true;
	checkWriteable();

	if(!$dirWriteable)
		error("请正确设置目录的可写属性，然后才能正常安装");
	else
		echo '<br /><input type="button" value="返回" onclick="history.go(-1);">&nbsp;<input type="button" value="继续" onclick="window.location=\'install.php?step=2\'">';
}
else if($_GET["step"] == "2")
{
?>
<p class="title2">第二步 配置基本信息</p>
<font color="red">注意：安装博客程序将删除同名的数据表，请一定记得做好数据备份</font>
<form method="POST" action="install.php">
<div id="dbconfig" class="sampleTabContent">
	<p>数据库服务器: <input type="text" name="DB_HOST" class="txt" value="localhost" /></p>
	<p>　数据库端口: <input type="text" name="DB_PORT" class="txt" value="3306" /></p>
	<p>数据库用户名: <input type="text" name="DB_USER" class="txt" /></p>
	<p>　数据库密码: <input type="text" name="DB_PWD" class="txt" /></p>
	<p>　数据库名称: <input type="text" name="DB_NAME" class="txt" /></p>
	<p>数据库表前缀: <input type="text" name="DB_PREFIX" class="txt" value="y_" /></p>
	<p>管理员用户名: <input type="text" name="user_login" class="txt" value="" /></p>
	<p>　管理员密码: <input type="password" name="user_pass" class="txt" value="" /></p>
	<p>　　密码确认: <input type="password" name="user_pass2" class="txt" value="" /></p>
	<p>　管理员邮箱: <input type="text" name="user_email" class="txt" value="" /></p>
	<p>　博客的网址: <input type="text" name="siteurl" class="txt" value="<?php echo str_replace("/install.php?step=2","","http://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]); ?>" /></p>
</div>
<input type="submit" name="install" value="安装">&nbsp;<input type="reset" name="reset" value="重填">
</form>
<?php
}
else
{
?>
<p class="title2">YBlog介绍</p>
<p>欢迎使用YBlog，这是一个基于<a href="http://www.thinkphp.cn" target="_blank">ThinkPHP</a>框架的单用户博客系统。</p>
<p>请确保你的系统满足以下安装条件：<br /><ul><li>PHP 5.2.0及以上版本</li><li>开启新评论的邮件通知需要PHP有权限主动向外发起连接</li><li>向外发送日志的引用通告需要PHP有权限主动向外发起连接</li></ul></p>
<p>进入下一步安装文件装检查安装目录的可写状态。</p>
<input type="button" value="继续" onclick="window.location='install.php?step=1'">
<?php
}
?>
</body>
</html>